import * as Cesium from 'cesium';

class MapLevelZoom {
  constructor(viewer, worker) {
    this.viewer = viewer;
    this.mouseWheelListener = null; // 用于存储事件监听器的引用
    this.worker = worker
    this.mapZoomCfg = [
      [10000000, 500000000], // 0
      [10000000, 500000000], // 1
      [5000000, 10000000],    // 2
      [3000000, 5000000],     // 3
      [2000000, 3000000],     // 4
      [1000000, 2000000],     // 5
      [900000, 1000000],      // 6
      [500000, 900000],      // 7
      [300000, 500000],      // 8
      [200000, 300000],      // 9
      [150000, 200000],      // 10
      [100000, 150000],      // 11
      [80000, 100000],      // 12
      [50000, 80000],      // 13
      [30000, 50000],      // 14
      [10000, 30000],      // 15
      [9500, 10000],       // 16
      [9000, 9500],       // 17
      [8000, 9000],       // 18
      [7000, 8000],       // 19
      [6000, 7000],       // 20
      [5000, 6000],       // 21
      [4000, 5000],       // 22
      [3000, 4000],       // 23
      [2000, 3000],       // 24
      [1000, 2000],       // 25
      [100, 1000],
      [10, 100],
      [1, 10]
    ]
  }
  // 创建鼠标滚轮监听事件
  createMouseWheelListener () {
    // 获取 canvas 元素
    const canvas = this.viewer.canvas;
    // 为 canvas 添加鼠标滚轮事件监听
    this.mouseWheelListener = (event) => {
      // 防止事件冒泡
      event.preventDefault();
      // 获取滚轮事件的 delta 值，正值表示向上滚动，负值表示向下滚动
      const delta = event.deltaY;
      // 在事件监听器内部获取当前高度
      const cameraPosition = this.viewer.camera.position;
      const ellipsoid = this.viewer.scene.globe.ellipsoid;
      const cartographic = ellipsoid.cartesianToCartographic(cameraPosition);
      const height = cartographic.height;
      let zoomIndex = 1
      this.mapZoomCfg.forEach((element, index) => { if (height >= element[0] && height <= element[1]) { zoomIndex = index } });
      this.worker.value.postMessage({ zoom: zoomIndex, height: height });
      // 根据滚轮方向调整相机的视距
      if (delta > 0) {
        // 向上滚动，放大地球
        console.log('放大');
      } else {
        // 向下滚动，缩小地球
        console.log('缩小');
      }
    };
    canvas.addEventListener('wheel', this.mouseWheelListener, false);
  }

  // 移除鼠标滚轮监听事件
  removeMouseWheelListener () {
    if (this.mouseWheelListener) {
      const canvas = this.viewer.canvas;
      canvas.removeEventListener('wheel', this.mouseWheelListener, false);
      this.mouseWheelListener = null; // 清除引用
    }
  }
}

export default MapLevelZoom;